<template>
  <el-dialog
    v-model="dialogVisible"
    title="短信统计分析"
    width="1200px"
    :close-on-click-modal="false"
  >
    <div class="statistics-container">
      <!-- 统计时间选择 -->
      <div class="time-selector">
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button value="today">今日</el-radio-button>
          <el-radio-button value="week">本周</el-radio-button>
          <el-radio-button value="month">本月</el-radio-button>
          <el-radio-button value="quarter">本季度</el-radio-button>
          <el-radio-button value="year">本年</el-radio-button>
          <el-radio-button value="custom">自定义</el-radio-button>
        </el-radio-group>
        
        <div v-if="timeRange === 'custom'" class="custom-time">
          <el-date-picker
            v-model="customTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleCustomTimeChange"
          />
        </div>
        
        <div class="time-actions">
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button @click="exportReport">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
        </div>
      </div>

      <!-- 总体统计卡片 -->
      <div class="overview-cards">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Message /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overviewData.total }}</div>
              <div class="stat-label">总发送量</div>
              <div class="stat-trend" :class="overviewData.totalTrend > 0 ? 'up' : 'down'">
                <el-icon><CaretTop v-if="overviewData.totalTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overviewData.totalTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overviewData.success }}</div>
              <div class="stat-label">发送成功</div>
              <div class="stat-rate success">{{ overviewData.successRate }}%</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon failed">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ overviewData.failed }}</div>
              <div class="stat-label">发送失败</div>
              <div class="stat-rate failed">{{ overviewData.failedRate }}%</div>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon cost">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">¥{{ overviewData.cost }}</div>
              <div class="stat-label">总费用</div>
              <div class="stat-trend" :class="overviewData.costTrend > 0 ? 'up' : 'down'">
                <el-icon><CaretTop v-if="overviewData.costTrend > 0" /><CaretBottom v-else /></el-icon>
                {{ Math.abs(overviewData.costTrend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 发送趋势图 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>发送趋势</span>
                  <el-select v-model="trendChartType" size="small" style="width: 100px">
                    <el-option label="按小时" value="hour" />
                    <el-option label="按天" value="day" />
                    <el-option label="按周" value="week" />
                    <el-option label="按月" value="month" />
                  </el-select>
                </div>
              </template>
              <div ref="trendChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          
          <!-- 成功率分析 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <span>成功率分析</span>
              </template>
              <div ref="successRateChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" style="margin-top: 20px">
          <!-- 短信类型分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <span>短信类型分布</span>
              </template>
              <div ref="typeDistributionChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
          
          <!-- 失败原因分析 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <span>失败原因分析</span>
              </template>
              <div ref="failureReasonChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 详细数据表格 -->
      <div class="data-table-section">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>详细数据</span>
              <div class="header-actions">
                <el-select v-model="tableGroupBy" size="small" style="width: 120px">
                  <el-option label="按日期" value="date" />
                  <el-option label="按类型" value="type" />
                  <el-option label="按发送人" value="sender" />
                </el-select>
                <el-button size="small" @click="exportTableData">
                  <el-icon><Download /></el-icon>
                  导出
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="tableData" style="width: 100%">
            <el-table-column :prop="getTableColumnProp()" :label="getTableColumnLabel()" width="150" />
            <el-table-column prop="total" label="总数" width="100" />
            <el-table-column prop="success" label="成功" width="100" />
            <el-table-column prop="failed" label="失败" width="100" />
            <el-table-column prop="successRate" label="成功率" width="100">
              <template #default="{ row }">
                <span :class="getSuccessRateClass(row.successRate)">{{ row.successRate }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="费用(元)" width="100" />
            <el-table-column prop="avgResponseTime" label="平均响应时间(秒)" width="150" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" size="small" link @click="viewDetails(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="table-pagination">
            <el-pagination
              v-model:current-page="tablePage"
              v-model:page-size="tablePageSize"
              :total="tableData.length"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              small
            />
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Download, 
  Message, 
  CircleCheck, 
  CircleClose, 
  Money,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 图表引用
const trendChartRef = ref()
const successRateChartRef = ref()
const typeDistributionChartRef = ref()
const failureReasonChartRef = ref()

// 图表实例
let trendChart: echarts.ECharts | null = null
let successRateChart: echarts.ECharts | null = null
let typeDistributionChart: echarts.ECharts | null = null
let failureReasonChart: echarts.ECharts | null = null

// 时间范围
const timeRange = ref('today')
const customTimeRange = ref([])

// 图表类型
const trendChartType = ref('hour')

// 表格相关
const tableGroupBy = ref('date')
const tablePage = ref(1)
const tablePageSize = ref(20)

// 总体统计数据
const overviewData = reactive({
  total: 15420,
  success: 14856,
  failed: 564,
  successRate: 96.3,
  failedRate: 3.7,
  cost: 1542.0,
  totalTrend: 12.5,
  costTrend: -8.3
})

// 表格数据
const tableData = ref([
  {
    date: '2024-01-15',
    type: '通知短信',
    sender: '张三',
    total: 1250,
    success: 1205,
    failed: 45,
    successRate: 96.4,
    cost: 125.0,
    avgResponseTime: 2.3
  },
  {
    date: '2024-01-14',
    type: '验证码',
    sender: '李四',
    total: 2180,
    success: 2156,
    failed: 24,
    successRate: 98.9,
    cost: 218.0,
    avgResponseTime: 1.8
  },
  {
    date: '2024-01-13',
    type: '告警短信',
    sender: '王五',
    total: 85,
    success: 82,
    failed: 3,
    successRate: 96.5,
    cost: 8.5,
    avgResponseTime: 2.1
  }
])

// 处理时间范围变化
const handleTimeRangeChange = (value: string) => {
  if (value !== 'custom') {
    customTimeRange.value = []
  }
  refreshData()
}

// 处理自定义时间变化
const handleCustomTimeChange = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  // 模拟数据刷新
  ElMessage.success('数据已刷新')
  
  // 更新图表
  nextTick(() => {
    updateCharts()
  })
}

// 导出报告
const exportReport = () => {
  ElMessage.success('统计报告导出成功')
}

// 导出表格数据
const exportTableData = () => {
  ElMessage.success('表格数据导出成功')
}

// 获取表格列属性
const getTableColumnProp = () => {
  const props: Record<string, string> = {
    date: 'date',
    type: 'type',
    sender: 'sender'
  }
  return props[tableGroupBy.value] || 'date'
}

// 获取表格列标签
const getTableColumnLabel = () => {
  const labels: Record<string, string> = {
    date: '日期',
    type: '类型',
    sender: '发送人'
  }
  return labels[tableGroupBy.value] || '日期'
}

// 获取成功率样式类
const getSuccessRateClass = (rate: number) => {
  if (rate >= 95) return 'success-rate-high'
  if (rate >= 90) return 'success-rate-medium'
  return 'success-rate-low'
}

// 查看详情
const viewDetails = (row: any) => {
  ElMessage.info(`查看${row.date || row.type || row.sender}的详细数据`)
}

// 初始化图表
const initCharts = () => {
  // 发送趋势图
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['发送总数', '成功数量', '失败数量']
      },
      xAxis: {
        type: 'category',
        data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '发送总数',
          type: 'line',
          data: [120, 200, 150, 800, 700, 300],
          smooth: true
        },
        {
          name: '成功数量',
          type: 'line',
          data: [115, 195, 145, 770, 680, 290],
          smooth: true
        },
        {
          name: '失败数量',
          type: 'line',
          data: [5, 5, 5, 30, 20, 10],
          smooth: true
        }
      ]
    }
    trendChart.setOption(trendOption)
  }

  // 成功率分析图
  if (successRateChartRef.value) {
    successRateChart = echarts.init(successRateChartRef.value)
    const successRateOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}%'
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value',
        min: 90,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          type: 'bar',
          data: [96.5, 97.2, 95.8, 98.1, 96.9, 94.3, 97.5],
          itemStyle: {
            color: function(params: any) {
              const colors = ['#67c23a', '#e6a23c', '#f56c6c']
              if (params.value >= 97) return colors[0]
              if (params.value >= 95) return colors[1]
              return colors[2]
            }
          }
        }
      ]
    }
    successRateChart.setOption(successRateOption)
  }

  // 短信类型分布图
  if (typeDistributionChartRef.value) {
    typeDistributionChart = echarts.init(typeDistributionChartRef.value)
    const typeDistributionOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '短信类型',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 8520, name: '通知短信' },
            { value: 4200, name: '验证码' },
            { value: 1850, name: '告警短信' },
            { value: 850, name: '营销短信' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    typeDistributionChart.setOption(typeDistributionOption)
  }

  // 失败原因分析图
  if (failureReasonChartRef.value) {
    failureReasonChart = echarts.init(failureReasonChartRef.value)
    const failureReasonOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: ['号码停机', '号码错误', '内容违规', '网络超时', '其他']
      },
      series: [
        {
          type: 'bar',
          data: [245, 156, 89, 45, 29],
          itemStyle: {
            color: '#f56c6c'
          }
        }
      ]
    }
    failureReasonChart.setOption(failureReasonOption)
  }
}

// 更新图表
const updateCharts = () => {
  // 这里可以根据时间范围更新图表数据
  if (trendChart) {
    // 更新趋势图数据
  }
  if (successRateChart) {
    // 更新成功率图数据
  }
  if (typeDistributionChart) {
    // 更新类型分布图数据
  }
  if (failureReasonChart) {
    // 更新失败原因图数据
  }
}

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    nextTick(() => {
      initCharts()
    })
  }
})

// 监听趋势图类型变化
watch(trendChartType, () => {
  updateCharts()
})

// 监听表格分组变化
watch(tableGroupBy, () => {
  // 重新加载表格数据
  refreshData()
})

// 组件卸载时销毁图表
const destroyCharts = () => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (successRateChart) {
    successRateChart.dispose()
    successRateChart = null
  }
  if (typeDistributionChart) {
    typeDistributionChart.dispose()
    typeDistributionChart = null
  }
  if (failureReasonChart) {
    failureReasonChart.dispose()
    failureReasonChart = null
  }
}

// 监听对话框关闭
watch(() => props.visible, (visible) => {
  if (!visible) {
    destroyCharts()
  }
})
</script>

<style scoped>
.statistics-container {
  height: 80vh;
  overflow-y: auto;
}

.time-selector {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.custom-time {
  margin-left: 10px;
}

.time-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 15px;
}

.stat-icon.total {
  background-color: #e3f2fd;
  color: #1976d2;
}

.stat-icon.success {
  background-color: #e8f5e8;
  color: #4caf50;
}

.stat-icon.failed {
  background-color: #ffebee;
  color: #f44336;
}

.stat-icon.cost {
  background-color: #fff3e0;
  color: #ff9800;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  font-weight: 500;
}

.stat-trend.up {
  color: #f56c6c;
}

.stat-trend.down {
  color: #67c23a;
}

.stat-rate {
  font-size: 12px;
  font-weight: 500;
}

.stat-rate.success {
  color: #67c23a;
}

.stat-rate.failed {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  height: 350px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.chart-container {
  height: 280px;
  width: 100%;
}

.data-table-section {
  margin-bottom: 20px;
}

.table-pagination {
  margin-top: 15px;
  text-align: right;
}

.success-rate-high {
  color: #67c23a;
  font-weight: 500;
}

.success-rate-medium {
  color: #e6a23c;
  font-weight: 500;
}

.success-rate-low {
  color: #f56c6c;
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-radio-button__inner) {
  padding: 8px 15px;
}
</style>